#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <ctime>
#include <cstdlib>
#include <cstdio>

class tickets
{
    private:
    int tickets;
    pthread_mutex_t mtx;

    public:
    Ticket():tickets(1000)
    {
        pthresd_mutex_init(&mtx,nullptr);
    }

    void GetTicket()
    {
        bool res=true;
        pthread_mutex_lock(&mtx);
        if(tickets>0)
        {
            std::cout<<"我是["<<pthread_self()<<"]我要抢的票是： "<<tickets<<std::endl;
            usleep(10000);
            tickets--;
            
        }
        else
        {
            printf("票已经被抢空了\n");
            res=false;
        }
        pthread_mutex_unlock(&mtx);

        return res;
    }

    ~Ticket()
    {
        pthreaad_mutex_destroy(&mtx);
    }
}

void *ThreadRuoution(void *args)
{
    //int id=*(int*)args;
    //delete (int*)args;

    Ticket *t =(Ticket*)args;

    while(true)
    {
        t->GetTicket()?continue:break;
        //std::cout<<tname<<" is running  ... "<<std::endl;
        //sleep(1);
    }
}

int main()
{
    Ticket *t=new Ticket(); 
    pthread_t tid[5];
    for(int i=0;i<5;i++)
    {
        int *id=new int(i);
        pthread_create(tid+i,nullptr,ThreadRuoution,id,(void*)t);
    }

    for(int i=0;i<5;i++)
    {
        pthread_join(tid[i],nullptr);

    }
    return 0;
}
